package com.support.widget;

import android.app.Activity;

import java.util.Stack;

/**
 * Created by hdb on 2017/2/21.
 */

public class ActivityStackManager {
    private static Stack<Activity> activityStack;
    private static ActivityStackManager instance;

    private ActivityStackManager() {
    }

    public static ActivityStackManager getScreenManager() {
        if(instance == null) {
            instance = new ActivityStackManager();
        }

        return instance;
    }

    public void popActivity() {
        Activity activity = (Activity)activityStack.lastElement();
        if(activity != null) {
            activity.finish();
            activity = null;
        }

    }

    protected void popActivity(Activity activity) {
        if(activity != null) {
            activity.finish();
            activityStack.remove(activity);
            activity = null;
        }

    }

    protected Activity currentActivity() {
        if(activityStack.size() == 0) {
            return null;
        } else {
            Activity activity = (Activity)activityStack.lastElement();
            return activity;
        }
    }

    public void pushActivity(Activity activity) {
        if(activityStack == null) {
            activityStack = new Stack();
        }

        activityStack.add(activity);
    }

    protected void popAllActivityExceptOne(Class<?> cls) {
        while(true) {
            Activity activity = this.currentActivity();
            if(activity == null || activity.getClass().equals(cls)) {
                return;
            }

            this.popActivity(activity);
        }
    }

    protected void popAllActivity() {
        while(true) {
            Activity activity = this.currentActivity();
            if(activity == null) {
                return;
            }

            this.popActivity(activity);
        }
    }

    protected void popAllActivityExceptHome(Class<? extends Activity> cls) {
        while(true) {
            Activity activity = this.currentActivity();
            if(activity == null) {
                return;
            }

            if(activity.getClass().getName().equals(cls.getName())) {
                activityStack.remove(activityStack.lastElement());
            } else {
                this.popActivity(activity);
            }
        }
    }
}
